<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getRoleList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="insertDialogVisible = true">新增角色</el-button>
      </template>
      <template #createDate="scope">
        {{ scope.row.createDate.replace("T", " ").split(".")[0] }}
      </template>
      <template #updateDate="scope">
        {{ scope.row.updateDate.replace("T", " ").split(".")[0] }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="openUpdateDialog(scope.row)">编辑</el-button>
        <el-button type="primary" v-show="scope.row.status !== 1" link :icon="Refresh" @click="updateRoleStatus(scope.row, 1)">
          恢复
        </el-button>
        <el-button type="primary" v-show="scope.row.status === 1" link :icon="Delete" @click="updateRoleStatus(scope.row, -1)">
          禁用
        </el-button>
        <el-button type="primary" v-show="scope.row.status === 1" link :icon="Delete" @click="updateRoleStatus(scope.row, -1)">
          删除
        </el-button>
      </template>
    </ProTable>
    <!-- 新增对话框 -->
    <el-dialog width="50%" v-model="insertDialogVisible" title="新增角色">
      <el-row :gutter="15">
        <el-col :span="12">
          <el-card class="box-card">
            <template #header>
              <span>基础信息</span>
            </template>
            <el-form :model="insertParam" :rules="ruleForm" label-width="100px" class="demo-ruleForm" style="height: 300px">
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="insertParam.roleName" />
              </el-form-item>
              <el-form-item label="排序号码" prop="orderNum">
                <el-input-number v-model="insertParam.orderNum"></el-input-number>
              </el-form-item>
              <el-form-item label="状态">
                <el-radio-group v-model="insertParam.status">
                  <el-radio :label="0">禁用</el-radio>
                  <el-radio :label="1">正常</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="insertParam.remark" type="textarea"></el-input>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="box-card">
            <template #header>
              <span>权限菜单</span>
            </template>
            <div style="height: 300px; overflow-y: auto">
              <TreeFilter multiple :request-api="getMenuTree" @change="addDialogChangeTreeFilter" />
            </div>
          </el-card>
        </el-col>
      </el-row>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="insertDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="insertRole">新增</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog width="50%" v-model="updateDialogVisible" title="修改角色信息">
      <el-row :gutter="15">
        <el-col :span="12">
          <el-card class="box-card">
            <template #header>
              <span>基础信息</span>
            </template>
            <el-form :model="updateParam" :rules="ruleForm" label-width="100px" class="demo-ruleForm" style="height: 300px">
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="updateParam.roleName" />
              </el-form-item>
              <el-form-item label="排序号码" prop="orderNum">
                <el-input-number v-model="updateParam.orderNum"></el-input-number>
              </el-form-item>
              <el-form-item label="状态">
                <el-radio-group v-model="updateParam.status">
                  <el-radio :label="0">禁用</el-radio>
                  <el-radio :label="1">正常</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="updateParam.remark" type="textarea"></el-input>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="box-card">
            <template #header>
              <span>权限菜单</span>
            </template>
            <div style="height: 300px; overflow-y: auto">
              <TreeFilter
                multiple
                :ref="updateTreeRef"
                label="label"
                value="value"
                :request-api="getMenuTree"
                :default-value="updateParam.menuIdList"
                @change="updateDialogChangeTreeFilter"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateRoleInfo">修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts" name="roleManage">
import { ref, reactive, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import TreeFilter from "@/components/TreeFilter/index.vue";
import type { FormInstance, FormRules } from "element-plus";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, ElementPlus } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CreateRoleParam, EditRoleInfoParam, EditRoleStatusParam, SysRole } from "@/api/interface/auth/role";
import { statusEnum, statusFieldNames } from "@/enums/httpEnum";
import { createRole, editRoleInfo, editRoleStatus, getRoleList, getRoleDetail } from "@/api/modules/auth/role";
import { MenuTreeResult } from "@/api/interface/auth/menu";
import { getMenuTree } from "@/api/modules/auth/menu";

// ProTable 实例
const proTable = ref<ProTableInstance>();

/** 新增对话框是否可见 */
const insertDialogVisible = ref(false);

/** 修改对话框是否可见 */
const updateDialogVisible = ref(false);

const updateTreeRef = ref<any>();

/** 是否是新增 */
const isAdd = ref(false);

const initInsertParam = {
  roleName: "",
  remark: "",
  orderNum: 0,
  status: 1,
  menuIdList: []
};

/** 新增参数 */
const insertParam = reactive<CreateRoleParam>({
  roleName: "",
  remark: "",
  orderNum: 0,
  status: 1,
  menuIdList: []
});

/** 修改参数 */
let updateParam = reactive<EditRoleInfoParam>({
  roleId: "",
  roleName: "",
  remark: "",
  orderNum: 0,
  status: 1,
  menuIdList: []
});

const ruleForm = reactive<FormRules>({
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  orderNum: [{ required: true, message: "请输入排序号码", trigger: "blur" }]
});

const columns = reactive<ColumnProps<SysRole>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { type: "index", label: "", width: 80 },
  {
    prop: "roleName",
    label: "角色名称",
    search: { el: "input", tooltip: "请输入角色名称" }
  },
  {
    prop: "orderNum",
    label: "排序"
  },
  {
    prop: "status",
    label: "状态",
    tag: true,
    enum: statusEnum,
    search: { el: "select", props: { filterable: true } },
    fieldNames: statusFieldNames
  },
  {
    prop: "createDate",
    label: "创建时间",
    width: 200
  },
  {
    prop: "updateDate",
    label: "修改时间",
    width: 200
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

const addDialogChangeTreeFilter = (val: string[]) => {
  insertParam.menuIdList = val;
};

const updateDialogChangeTreeFilter = (val: string[]) => {
  updateParam.menuIdList = val;
};

const openUpdateDialog = async (param: SysRole) => {
  let { data } = await getRoleDetail({ roleId: param.roleId });
  Object.assign(updateParam, data); // 保持响应式，只更新字段
  updateDialogVisible.value = true;
};

/** 修改角色信息 */
const updateRoleInfo = async () => {
  await editRoleInfo(updateParam);
  await proTable.value?.getTableList();
  updateDialogVisible.value = false;
  ElMessage.success("修改成功");
};

/** 修改角色状态 */
const updateRoleStatus = async (param: SysRole, status: number) => {
  await editRoleStatus({ roleId: param.roleId, status: status });
  await proTable.value?.getTableList();
  ElMessage.success("修改状态成功");
};

/** 新增角色 */
const insertRole = async () => {
  await createRole(insertParam);
  insertDialogVisible.value = false;
  await proTable.value?.getTableList();
  Object.assign(insertParam, initInsertParam);
  ElMessage.success("新增成功");
};
</script>
